﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using Utils.Extensions;
using Utils.Wpf;

namespace StockAnalyst2.Plugins.Visualization.Realtime
{
	internal class NotificationViewerVM : ViewModelBase
	{
		#region Properties

		public ObservableCollection<NotificationViewerRowVM> Rows { get; private set; }
		public ObservableCollection<Notification> Model { get; private set; } 

		#endregion

		#region Public Methods

		public NotificationViewerVM()
		{
			this.Rows = new ObservableCollection<NotificationViewerRowVM>();
			this.Model = new ObservableCollection<Notification>();

			this.Model.CollectionChanged += this.Model_CollectionChanged; // Local object
		}

		#endregion

		#region Event Handlers

		private void Model_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
		{
			if (e.Action == NotifyCollectionChangedAction.Add)
			{
				foreach (Notification notification in e.NewItems)
				{
					this.InsertRow(new NotificationViewerRowVM(notification));
				}
			}
		}

		#endregion

		#region Private Methods

		private void InsertRow(NotificationViewerRowVM row)
		{
			if (base.Dispatcher.CheckAccess())
			{
				if (this.Rows.Count >= Properties.Settings.Default.MaxRealtimeNotifications)
				{
					this.Rows.RemoveAt(this.Rows.Count - 1);
				}
				this.Rows.Insert(0, row);	
			}
			else
			{
				base.Dispatcher.Invoke(new Action<NotificationViewerRowVM>(this.InsertRow), new object[] {row});
			}
		}

		#endregion
	}
}
